<?php
/**
* Copyright (c) 2002-2007 BioWare Corp.
* http://www.bigdaddymonitor.org
*
* This file is part of the BigDaddy Monitoring
* program. It is free software distributed under
* the terms of the BSD License. It is ditributed
* in the hopes that it will be useful, but
* WITHOUT ANY WARRANTY; without event the implied
* warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE.
*
* The BSD License is available from:
* http://www.opensource.org/licenses/bsd-license.php
**/
/*--------------------------------------------------------------------------------------
 Class::Audit
 Created by Duleepa Wijayawardhana
 August 26, 2005

 Description: This class allows access to the Audit database table so that
 we can audit any application. Documentation on this is available here:
 http://staff.bioware.com/wiki/index.html?action=view&wiki=websystems&page=AuditMain
 
 --------------------------------------------------------------------------------------*/
class Audit
{
    
    /*---------------------------------------------------------------------------------
      void __contstruct ()
      Created by Duleepa Wijayawardhana
      August 25, 2005
      
      Description: Class constructor
      ---------------------------------------------------------------------------------*/
    public function __construct()
    {

    }
    /*---------------------------------------------------------------------------------
      int SetAudit ($aInfo, $sApplication)
      Created by Duleepa Wijayawardhana
      August 26, 2005
      
      Description: Sets data into the audit table for string sApplication
      
      aInfo structure
      modifiedDate => UNIX_TIMESTAMP() (int) if not set it will use the current time
      userID => numeric userID
      userIDAffected => numeric userID
      username => if not set it will always used LOGGEDIN_USERNAME (internally)
      usernameAffected => string username
      primaryNumericID => integerID (unsigned)
      secondaryNumericID => integerID (unsigned)
      primaryStringID => string (255 char)
      secondaryStringID => string (255 char)
      time => string (80 char)
      action => string (80 char)
      comment => text
      
      Returns:
      
      -1 => No Array of Info
      -2 => No Application set
      -3 => Insert Failed
      
      positive insertID on success
      
      ---------------------------------------------------------------------------------*/
    public function SetAudit($aInfo, $sApplication)
    {
        //No Array
        if (!is_array($aInfo))
        {
            return -1;
        }
        
        //No Application
        if ($sApplication=="" || !$sApplication)
        {
            return -2;
        }
        
        //If modifiedDate is not set to anything or is 0 then we
        //set the current time. We are expecting a UNIX_TIMESTAMP() int
        if ($aInfo["modifiedDate"]=="" || $aInfo["modifiedDate"]==0)
        {
            $sModifiedDate=ConvertUnixToMySQLDateTimeString(time());
        }
        else
        {
            $sModifiedDate=ConvertUnixToMySQLDateTimeString($aInfo["modifiedDate"]);
        }
        
        //If username is not passed in then we will use the current logged in username
        if ($aInfo["username"]!="")
        {
            $sUsername=$aInfo["username"];
        }
        else
        {
            if (defined("LOGGEDIN_USERNAME"))
            {
                $sUsername=LOGGEDIN_USERNAME;
            }
        }
        
        //Insert in
        $sql="INSERT INTO auditData SET
            application='".$sApplication."',
            modifiedDate='".$sModifiedDate."',
            userID = '".$aInfo["userID"]."',
            userIDAffected = '".$aInfo["userIDAffected"]."',
            username='".$sUsername."',
            usernameAffected='".$aInfo["usernameAffected"]."',
            primaryNumericID='".$aInfo["primaryNumericID"]."',
            secondaryNumericID='".$aInfo["secondaryNumericID"]."',
            primaryStringID='".$aInfo["primaryStringID"]."',
            secondaryStringID='".$aInfo["secondaryStringID"]."',
            type='".$aInfo["type"]."',
            action='".$aInfo["action"]."',
            comment='".$aInfo["comment"]."'";
        $aOptions = array(
        "getInsertID" => true,
        "dbHandle" => "bigdaddystats"
        );
        $nInsertID=db_query($sql, $aOptions);
        
        if ($nInsertID>0)
        {
            return $nInsertID;
        }
        else
        {
            //Some kind of failure
            return -3;
        }

    }

    /*---------------------------------------
      void getAuditData(hash $aFilter, string $sSort, bool $bSortDescending)

      Author: Jesse van Herk <jesse@bioware.com>

      Description:
        retrieve a list of audit data matching the given filters, sorted in the given order.

      Args: 
            $aFilter:  a hash like: array( 'application' => 'someApp', 'type' => 'someType',...)
                    possible field names are:
                        ID
                        application
                        modifiedDate
                        userID
                        userIDAffected
                        username
                        usernameAffected
                        primaryNumericID
                        secondaryNumericID
                        primaryStringID
                        secondaryStringID
                        type
                        action
                        comment

            $sSort:  the field on which to sort the results.  Must be a valid field as listed above.
            $bSortDescending: whether to sort in desccending order. default false.

      Returns:
            -1 if no filter or invalid filter.
            -2 if no results.
            array of results otherwise

    ------------------------------------------*/
    public function getAuditData($aFilter, $sSort = '', $bSortDescending = false, $nLimit = NULL)
    {
        if(!is_array($aFilter))
        {
            return -1;
        }

        // these are all of the columns in the auditData table.
        $aPotentialFields = array( 'ID', 'application', 'modifiedDate', 'userID', 'userIDAffected', 'username', 'usernameAffected', 'primaryNumericID', 'secondaryNumericID', 'primaryStringID', 'secondaryStringID', 'type', 'action', 'comment');
        $aAuditFields = array();

        foreach ($aPotentialFields as $sField)
        {
            $sValue = db_escape_string($aFilter[$sField]);
            if(strlen($sValue) > 0)
            {
                if($sField == 'comment')
                {
                    $aAuditFields[] = "$sField LIKE '%$sValue%'";
                }
                elseif($sField == 'modifiedDate') 
                {
                    // it comes in as a single timestamp. if it is not specific, turn it into a range.
                    preg_match("/(\d+)-(\d+)-(\d+)(.*)/", $sValue, $aMatches);
                    $nYear = $aMatches[1];
                    $nMonth = $aMatches[2];
                    $nDay = $aMatches[3];
                    $sStartDate = "$nYear-$nMonth-$nDay 00:00:00";
                    $sEndDate = "$nYear-$nMonth-$nDay 23:59:59";
                    $aAuditFields[] = "$sField BETWEEN '$sStartDate' AND '$sEndDate'";
                }
                else
                {
                    $aAuditFields[] = "$sField='$sValue'";
                }
            }

        }

        if(is_array($aAuditFields) && count($aAuditFields) > 0)
        {
            $sFilterSQL = join(' AND ', $aAuditFields);
        }
        else
        {
            return -1;
        }

        $sSortSQL = '';
        if(in_array($sSort, $aPotentialFields))
        {
            $sDirection = '';
            if($bSortDescending) // sort descending
            {
                $sDirection = " DESC";
            }
            $sSortSQL = " ORDER BY $sSort $sDirection";
        }

        $sql = "SELECT * FROM auditData WHERE $sFilterSQL $sSortSQL";
        
        if ($nLimit != NULL && $nLimit >0)
        {
            $sql.=" LIMIT ".$nLimit;
        }
        
        $aResult = db_fetch_array(db_query($sql, array("dbHandle" => "bigdaddystats")));

        if(is_array($aResult))
        {
            return $aResult;
        }

        return -2;
    }
    
    
}

?>
